package org.example.management.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.management.entity.GoodsType;
import org.example.management.mapper.GoodsTypeMapper;
import org.example.management.service.IGoodsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class GoodsTypeServiceImpl extends ServiceImpl<GoodsTypeMapper, GoodsType> implements IGoodsTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //递归查询所有子节点
    private List<GoodsType> getChildren(GoodsType root, List<GoodsType> all, long top){
        return all.stream().filter(goodsType -> Objects.equals(goodsType.getTypePid(), root.getTypeId()))
                .map(goodsType -> {
                    stringRedisTemplate.opsForSet().add(String.valueOf(top), String.valueOf(goodsType.getTypeCode()));
                    goodsType.setChildren(getChildren(goodsType,all,top));
                    return goodsType;
                }).toList();
    }


    @Override
    public List<GoodsType> getAllTypeAndChildren(){
        List<Object> type = stringRedisTemplate.opsForHash().values("types");
        if (type.isEmpty()) {
            List<GoodsType> top=new QueryChainWrapper<>(baseMapper).eq("type_pid",0).list();
            List<GoodsType> all = baseMapper.selectList(null);
            return top.stream().peek(t -> {
                List<GoodsType> children = getChildren(t, all, t.getTypeCode());
                t.setChildren(children);
                stringRedisTemplate.opsForHash().put("types", String.valueOf(t.getTypeCode()), JSON.toJSONString(t));
            }).toList();
        }
        return type.stream().map(t ->
                JSON.parseObject((String) t, GoodsType.class)).toList();
    }


    /**
     * 查询编号对应的商品父类型
     * @param typeCode
     * @return
     */
    @Override
    public GoodsType findTopGoodsType(Long typeCode) {
        Set<Object> types = stringRedisTemplate.opsForHash().keys("types");

        GoodsType goodsType=null;
        for (Object type : types) {
            Boolean member = stringRedisTemplate.opsForSet().isMember((String) type, String.valueOf(typeCode));
            if (Boolean.TRUE.equals(member)){
                goodsType=JSON.parseObject((String) stringRedisTemplate.opsForHash().get("types",type), GoodsType.class);
                break;
            }
        }
        return goodsType;
    }



}
